import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Tabs } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import StandardTable from '@/components/StandardTable';
import TaskProgress from '../../components/TaskProgress';
import { urlParse } from '@/utils/utils';
import Authorized from '@/utils/Authorized';

const { TabPane } = Tabs;
@connect(({ charge, loading, chargebillns }) => ({
  charge,
  loading: loading.models.charge,
  noBillData: charge.noBillData, // 其它列表数据
  onceBillData: charge.onceBillData, // 一次性列表数据
  wageGenerationData: charge.wageGenerationData, // 代发工资代报税列表数据
  chargebillns,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      sendSuppId: '',
      billId: '',
      billYm: '',
      activeKey: '3',
      enterActiveKey: '1',
    };
  }

  componentDidMount() {
    const {
      location: { search },
    } = this.props;
    const { billId, billYm, sendSuppId, enterActiveKey } = this.state;
    const billIdParam = urlParse(search).billId || billId;
    const feeYm = urlParse(search).billYm || billYm;
    const sendSuppIdParam = urlParse(search).sendSuppId || sendSuppId;
    const enterActiveKeyNew = urlParse(search).enterActiveKey || enterActiveKey;
    this.setState(
      {
        billId: billIdParam,
        billYm: feeYm,
        sendSuppId: sendSuppIdParam,
        enterActiveKey: enterActiveKeyNew,
      },
      () => {
        this.getList(1, 10);
      }
    );
  }

  // 查看当前有无任务
  checkHasTask = () => {
    const { dispatch } = this.props;
    // 查看当前有无任务进行
    dispatch({
      type: 'charge/checkCreateBillTask',
    });
  };

  // 进度弹框显隐
  handleProgressModalVisible = flag => {
    const { dispatch } = this.props;
    if (!flag) {
      dispatch({
        type: 'chargebillns/updateModelData',
        payload: {
          showProgress: false,
        },
      });
    }
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { activeKey, sendSuppId, billYm } = this.state;
    const {
      location: { query },
      dispatch,
    } = this.props;
    const { creType } = query;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
    };
    let listUrl = null;
    switch (activeKey) {
      case '1': // 代发工资代收费
        listUrl = 'charge/getNsListWage';
        break;
      case '2': // 一次性收费
        listUrl = 'charge/getNsListOnce';
        break;
      case '3': // 其它
        listUrl = 'charge/getNsListAccuAndIns';
        break;
      default:
        listUrl = 'charge/getNsListAccuAndIns';
        break;
    }
    dispatch({
      type: listUrl,
      payload: {
        sendSuppId,
        billYm,
        pageArg,
        creType,
      },
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    if (activeKey === '3') {
      const {
        noBillData: { pagination },
      } = this.props;
      this.setState({ activeKey }, () => {
        this.getList(pagination.current, pagination.pageSize);
      });
    } else if (activeKey === '2') {
      const {
        onceBillData: { pagination },
      } = this.props;
      this.setState({ activeKey }, () => {
        this.getList(pagination.current, pagination.pageSize);
      });
    } else {
      const {
        wageGenerationData: { pagination },
      } = this.props;
      this.setState({ activeKey }, () => {
        this.getList(pagination.current, pagination.pageSize);
      });
    }
  };

  // 生成账单
  toBill = () => {
    const { dispatch } = this.props;
    const { sendSuppId, billYm, enterActiveKey } = this.state;
    dispatch({
      type: 'chargebillns/uploadFileWithProgress',
      payload: {
        batchType: enterActiveKey === '1' ? 3 : 4,
        params: { sendSuppId, billYm },
      },
    });
    // dispatch({
    //   type: enterActiveKey === '1' ? 'charge/createBill' : 'charge/createNoEnterBill',
    //   payload: {
    //     sendSuppId,
    //     billYm,
    //   },
    // }).then(res => {
    //   if (res.success) {
    //     if (res.data.taskCode === 1) {
    //       dispatch({
    //         type: 'charge/updateModelData',
    //         payload: {
    //           billTaskId: res.data.billTaskId,
    //         },
    //       });
    //       this.viewTaskProgress();
    //     } else if (res.data.taskCode === 3) {
    //       message.warning('当前有账单任务正在生成，请稍后操作！');
    //     }
    //   } else {
    //     message.warning(res.message || '服务端错误！');
    //   }
    // });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  render() {
    const {
      charge,
      loading,
      noBillData,
      onceBillData,
      wageGenerationData,
      chargebillns,
    } = this.props;
    const columnsWage = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '是否垫付',
        dataIndex: 'isSpotName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '个人所得税',
        dataIndex: 'taxblAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '实发工资',
        dataIndex: 'realAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '工资年月',
        dataIndex: 'busiYm',
        align: 'center',
        sorter: (a, b) => new Date(b.busiYm) - new Date(a.busiYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];
    const columnsOnce = [
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      // {
      //   title: '收费年月',
      //   dataIndex: 'feeYm',
      //   sorter: (a, b) => new Date(b.feeYm) - new Date(a.feeYm),
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      // },
      {
        title: '业务年月',
        dataIndex: 'busiYm',
        sorter: (a, b) => new Date(b.busiYm) - new Date(a.busiYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      },
      {
        title: '金额',
        dataIndex: 'feeAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '产品',
        dataIndex: 'pdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];
    const columnsOthers = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '证件号',
        dataIndex: 'cardNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
      // {
      //   title: '收费年月',
      //   dataIndex: 'feeYm',
      //   sorter: (a, b) => new Date(b.feeYm) - new Date(a.feeYm),
      //   onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      //   render: val => val && `${val.toString().substr(0, 4)}-${val.toString().substr(4, 5)}`,
      // },
      {
        title: '金额',
        dataIndex: 'realFeeAmo',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder', textAlign: 'right' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
      },
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card style={{ marginBottom: 24 }} bordered={false}>
          <Tabs defaultActiveKey="3" onChange={this.changeTabPane}>
            <TabPane tab="代发工资待报税" key="1">
              <StandardTable
                selectedRows={[]}
                selectedRowKeys={[]}
                rowSelection={null}
                loading={loading}
                data={wageGenerationData}
                rowKey="key"
                columns={columnsWage}
                onChange={this.handleStandardTableChange}
              />
            </TabPane>
            <TabPane tab="一次性收费" key="2">
              <StandardTable
                selectedRows={[]}
                selectedRowKeys={[]}
                rowSelection={null}
                loading={loading}
                data={onceBillData}
                rowKey="key"
                columns={columnsOnce}
                onChange={this.handleStandardTableChange}
              />
            </TabPane>
            <TabPane tab="其它" key="3">
              <StandardTable
                selectedRows={[]}
                selectedRowKeys={[]}
                rowSelection={null}
                loading={loading}
                data={noBillData}
                rowKey="empId"
                columns={columnsOthers}
                onChange={this.handleStandardTableChange}
              />
            </TabPane>
          </Tabs>
        </Card>
        <TaskProgress
          progressVisible={chargebillns.showProgress}
          progressPercent={chargebillns.progressPercent || 0}
          isShowResult={chargebillns.progressPercent === 100}
          resultInfo={chargebillns.resultInfo}
          checkHasTask={this.checkHasTask}
          handleProgressModalVisible={this.handleProgressModalVisible}
          closeModalCallBack={() => {
            if (Number(charge.progressPercent) === 100) {
              router.push('/chargmanage/chargebillns/index');
            }
          }}
        />
        <FooterToolbar style={{ width: '100%' }}>
          <Button style={{ marginRight: 10 }} onClick={() => window.history.back()}>
            关闭
          </Button>
          <Authorized authority="ns:nsBillChrg:createBill" noMatch={null}>
            <Button type="primary" onClick={this.toBill}>
              生成账单
            </Button>
          </Authorized>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default BasicList;
